package com.gowants.pems.service;

import com.gowants.pems.mapper.EquipmentFaultMapper;
import com.gowants.pems.mapper.EquipmentMapper;
import com.gowants.pems.model.Equipment;
import com.gowants.pems.model.EquipmentFault;
import com.gowants.pems.model.EquipmentFaultFile;
import com.gowants.pems.model.EquipmentFile;
import com.gowants.pems.util.Const;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.UploadUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EquipmentFaultService {

    @Autowired
    private EquipmentMapper eMapper;
    @Autowired
    private EquipmentFaultMapper mapper;

    @Autowired
    private  ParamsService paramsService;

    /**
     * 新增设备
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int saveEquipmentFault(EquipmentFault equipment){
        int i=0;
        i=mapper.insert(equipment);
        if (equipment.getListFile()!=null && equipment.getListFile().size()>0) {
            List<EquipmentFaultFile> fileList = equipment.getListFile().stream().map(m -> {
                m.setId(UUID.randomUUID().toString());
                m.setPid(equipment.getId());
                m.setType(0);
                String suffix = m.getAddress().substring(m.getAddress().lastIndexOf(".") + 1, m.getAddress().length());
                if (isImage(suffix)) {
                    m.setType(1);
                }
                if ("xlsx".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix)) {
                    m.setType(2);
                }
                if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
                    m.setType(3);
                }
                if ("pdf".equalsIgnoreCase(suffix)) {
                    m.setType(4);
                }
                if (isVideo(suffix)) {
                    m.setType(5);
                }
                return m;
            }).collect(Collectors.toList());
            if(fileList.size()>0) {
                mapper.insertFile(fileList);
            }
            Equipment equipment1=new Equipment();
            equipment1.setId(equipment.getEquipmentId());
            equipment1.setState(2);
            eMapper.update(equipment1);
        }
        return i;
    }

    /**
     * 新增设备
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int editEquipmentFault(EquipmentFault equipment){
        int i=0;
        i= mapper.update(equipment);
        if (equipment.getListFile()!=null && equipment.getListFile().size()>0) {
            List<EquipmentFaultFile> fileList = equipment.getListFile().stream().map(m -> {
                m.setId(UUID.randomUUID().toString());
                m.setPid(equipment.getId());
                m.setType(0);
                String suffix = m.getAddress().substring(m.getAddress().lastIndexOf(".") + 1, m.getAddress().length() - 1);
                if (isImage(suffix)) {
                    m.setType(1);
                }
                if ("xlsx".equalsIgnoreCase(suffix) || "xls".equalsIgnoreCase(suffix)) {
                    m.setType(2);
                }
                if ("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix)) {
                    m.setType(3);
                }
                if ("pdf".equalsIgnoreCase(suffix)) {
                    m.setType(4);
                }
                if (isVideo(suffix)) {
                    m.setType(5);
                }
                return m;
            }).collect(Collectors.toList());
            if(fileList.size()>0) {
                mapper.insertFile(fileList);
            }
        }
        if(equipment.getState()==2){
            Equipment equipment1=new Equipment();
            equipment1.setId(equipment.getEquipmentId());
            equipment1.setState(1);
            eMapper.update(equipment1);
        }
        return i;
    }

    /**
     * 设备删除
     * @param id
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public int deleteEquipmentFault(String id){
        int i = 0;
        mapper.delete(id);
        List<EquipmentFaultFile> list = mapper.selectFile(id);
        String path = paramsService.getParamValueByNumber(Const.equipment_file_path);
        for (EquipmentFaultFile file : list){
            String address= file.getAddress();
            File f=new File(path+address);
            if(f.exists()){
                f.delete();
            }
        }
        i = mapper.deleteFileByPid(id);
        return i;
    }

    /**
     * 删除 设备文件
     * @param address
     * @return
     */
    public int deleteEquipmentFile(String address){
        int i=0;
        i = mapper.deleteFileByAddress(address);
        if(mapper.selectByAddress(address)==0){
            i=1;
        }
        String path = paramsService.getParamValueByNumber(Const.equipment_file_path);
        File file=new File(path+address);
        if(file.exists()){
            file.exists();
        }
        return i;
    }

    /**
     * <文件上传>
     *
     * @param myFile 文件 pathConfig 文件保存根路径 isRelpaceFileName 是否更换文件名 isCreateDir
     *               是否创建新文件夹 isRelpaceFileName true: 文件名_时间戳 isCreateDir true:
     *               按当前时间创建文件夹
     * @return
     * @remake
     */
    public String upload(MultipartFile myFile, String pathConfig, String relativePath, String mappingPath,
                         boolean isRelpaceFileName, boolean isCreateDir) {
        String result = "";
        String fileName = UploadUtil.getFileName(myFile);
        try {
            // 设置文件全限定名
            String path = paramsService.getParamValueByNumber(pathConfig);
            // 是否更换文件名
            if (isRelpaceFileName) {
                // fileName.
                // String[] fNames = fileName.split("\\.");
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
                Random rand = new Random();
                int x = rand.nextInt(999);
                String fNames = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
                fileName = df.format(new Date()) + x + "." + fNames;
            }
            // 是否创建文件夹
            if (isCreateDir) {
                String dir = DateUtil.getDays();
                fileName = dir + "/" + fileName;
            }
            // 拼接保存文件的全限定名
            String filePath = "";
            if (StringUtils.isNotBlank(relativePath)) {
                filePath += ("/" + relativePath);
            }
            filePath += ("/" + fileName);
            UploadUtil.saveFileFromInputStream(myFile.getInputStream(), path + filePath);
            // result = filePath.replace(path, "");
            result = filePath;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }


    /**
     * <上传文件校验大小及格式>
     *
     * @param
     * @return -1 大小不符合规定 0 上传类型不符合规定 1 校验通过
     * @remake create by GJR 2019/7/1 11:31
     */
    public int uploadCheck(MultipartFile myFile, String fileType, String fileSize) {
        if (!uploadFileSizeCheck(myFile, fileSize)) {
            return -1;
        }

        if (!uploadFileTypeCheck(myFile, fileType)) {
            return 0;
        }

        return 1;
    }

    /**
     * <上传文件校验>
     *
     * @param
     * @return
     * @remake
     */
    public boolean uploadFileSizeCheck(MultipartFile myFile, String fileSize) {
        // 文件大小不符合规定
        String size = paramsService.getParamValueByNumber(fileSize);

        // 未定义视为没限制
        if (null == size || "".equals(size)) {
            return true;
        }

        // 字节单位比较，数据库配置单位是MB
        if (myFile.getSize() > Long.valueOf(size) * 1024 * 1024) {
            return false;
        }

        return true;
    }

    /**
     * <文件格式校验>
     *
     * @param
     * @return
     * @remake
     */
    public boolean uploadFileTypeCheck(MultipartFile myFile, String fileType) {

        // 图片格式不符合规定
        String fileName = UploadUtil.getFileName(myFile);

        // 格式正则配置
        String type = paramsService.getParamValueByNumber(fileType);

        // 未定义视为没限制
        if (null == type || "".equals(type)) {
            return true;
        }

        if (!fileName.matches(type)) {
            return false;
        }
        return true;

    }

    private Boolean isImage(String suffix){
        boolean bool=false;
        List<String> format = new ArrayList<>();
        format.add("JPG");
        format.add("jpg");
        format.add("BMP");
        format.add("bmp");
        format.add("GIF");
        format.add("gif");
        format.add("WBMP");
        format.add("wbmp");
        format.add("PNG");
        format.add("png");
        format.add("JPEG");
        format.add("jpeg");
        if(format.contains(suffix)){
            bool =true;
        }
        return bool;
    }

    private Boolean isVideo(String suffix){
        boolean bool=false;
        List<String> format = new ArrayList<>();
        format.add("wmv");
        format.add("asf");
        format.add("asx");
        format.add("rm");
        format.add("rmvb");
        format.add("mp4");
        format.add("3gp");
        format.add("mov");
        format.add("m4v");
        format.add("avi");
        format.add("dat");
        format.add("mkv");
        format.add("flv");
        format.add("vob");
        if(format.contains(suffix.toLowerCase())){
            bool =true;
        }
        return bool;
    }

}
